/*---------------------------------------------------------------------
 * File name: hal_flash.c
 *
 * Copyright (c) <2020-2022>, <ChenLong>
 *
 * All rights reserved.
 *
 * Author: ChenLong
 * Email: worldlong@foxmail.com
 *--------------------------------------------------------------------*/
#include "stm32f30x_flash.h"
#include "hal_flash.h"
#include "hal_system.h"
#include "hal_config.h"
/*
*/
void HAL_Flash::unlock()
{  
  FLASH_Unlock(); 
}
/*
*/
void HAL_Flash::lock()
{  
  FLASH_Lock(); 
}
/*
*/
bool HAL_Flash::erase(uint32_t page_addr)
{  
  bool ret = false;
  
  uint32_t sr = enter_critical();
  if(FLASH_ErasePage(page_addr) == FLASH_COMPLETE) 
  {
    ret = true;
  }
  exit_critical(sr);
  return ret;
}
/*
*/
int HAL_Flash::write(uint32_t addr, uint32_t *data, int num)
{  
  uint32_t sr = enter_critical();
  for(int i = 0; i<num; i++)
  {
    if(FLASH_ProgramWord(addr + i*4, data[i]) != FLASH_COMPLETE)
    {
      exit_critical(sr);
      return i;
    }
  }
  exit_critical(sr);
  return num;
}

/*
read
*/
int HAL_Flash::read(uint32_t addr, uint32_t *data, int num)
{
  /* must 4Bytes align */
  if((addr%4) != 0) {return 0;}
  
  uint32_t sr = enter_critical();
  
  for(int i=0; i<num; i++)
  {
    data[i] = *(__IO uint32_t*)(addr + i*4);
  }
  exit_critical(sr);
  return num;
}






